//
//  SignalView.m
//  AffichageSignal
//
//  Created by Pierre DUCHENE on 09/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

#import "SignalView.h"
#import "SignalVisualizer.h"

@interface SignalView (PrivateMethods)
- (void)computeSignalPath;
@end

@implementation SignalView

@synthesize controller;
- (void)setController:(SignalVisualizer *)aController
{
	if (controller != aController) {
		[controller release];
		controller = aController;
	}
	
	// Abscissa Path
	CGMutablePathRef tempPath = CGPathCreateMutable();
	CGPathMoveToPoint(tempPath, nil, kXStart, 0);
	CGPathAddLineToPoint(tempPath, nil, kXStart, self.frame.size.height);
	abscissaPath = CGPathCreateCopy(tempPath);
	CGPathRelease(tempPath);
	
	// Ordinate Path
	tempPath = CGPathCreateMutable();
	CGPathMoveToPoint(tempPath, nil, 0, self.frame.size.height/2);
	CGPathAddLineToPoint(tempPath, nil, 2000, self.frame.size.height/2);
	ordinatePath = CGPathCreateCopy(tempPath);
	CGPathRelease(tempPath);
}

- (id)initWithFrame:(NSRect)frame {
    //self = [super initWithFrame:NSMakeRect(0, 0, 636, kViewHeight)];
    if (self = [super initWithFrame:frame]) {
		
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
	[self computeSignalPath];
    CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
	CGContextAddPath(context, signalPath);
	CGContextAddPath(context, abscissaPath);
	CGContextAddPath(context, ordinatePath);
	CGContextStrokePath(context);
}

- (void)computeSignalPath
{ 
	NSArray* values = [[controller model] values];
	CGFloat offset = self.frame.size.width / [values count];
	CGFloat currentX = kXStart;
	CGFloat zeroPosition = self.frame.size.height / 2;
	
	// Signal Path
	CGMutablePathRef tempPath = CGPathCreateMutable();
	CGPathMoveToPoint(tempPath, nil, currentX, self.frame.size.height/2); // Origin
	for (NSNumber* n in values) {
		float newY = zeroPosition * ([n floatValue]+1);
		CGPathAddLineToPoint(tempPath, nil, currentX, newY);
		currentX += offset;
	}
	signalPath = CGPathCreateCopy(tempPath);
	CGPathRelease(tempPath);
}

@end
